import {
  ConnectedSocket,
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
  WsException,
} from '@nestjs/websockets';
import { Server, Socket } from 'socket.io';
import { ChatService } from './chat.service';

@WebSocketGateway(80, { namespace: 'events', cors: { origin: '*' } })
export class SocketGateway implements OnGatewayConnection, OnGatewayDisconnect {
  @WebSocketServer()
  server: Server;

  constructor(private readonly chatService: ChatService) {}

  /**
   * 创建连接
   * @param client 连接终端
   */
  async handleConnection(client: Socket) {
    const token = client.handshake.auth?.token || client.handshake.query?.token;
    if (!token) {
      throw new WsException('Missing authentication token');
    }
    const { type, id } = await this.chatService.validateToken(token);
    // 将来role放入头部
    client['role'] = {
      type,
      id,
    };
    // 维护列表
    await this.chatService.online(client);
  }

  /**
   * 断开连接
   * @param client 连接终端
   */
  handleDisconnect(@ConnectedSocket() client: Socket) {
    //TODO 判断client是否存在于Redis中,存在则删除
    this.chatService.offline(client);
    console.log(client);
  }

  @SubscribeMessage('message')
  handleMessage(@ConnectedSocket() client: Socket, @MessageBody() data: any) {
    console.log(client);
    console.log(data);
  }
}
